<template>
  <div class="container">
    <div class="search-container">
      <el-form :inline="true" :model="searchForm" ref="searchFormRef">
        <el-form-item label="断奶日期">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="~"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            @change="handleDateRangeChange"
          />
        </el-form-item>
        <el-form-item label="种母耳号">
          <el-select 
            v-model="searchForm.earTag" 
            placeholder="请选择种母耳号" 
            clearable
            filterable
            style="width: 180px;"
          >
            <el-option 
              v-for="(name, id) in earNumberMap" 
              :key="id" 
              :label="name" 
              :value="id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="负责人">
          <el-select v-model="searchForm.responsiblePerson" placeholder="请选择负责人" clearable>
            <el-option
              v-for="user in responsiblePersonOptions"
              :key="user.value"
              :label="user.label"
              :value="user.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 新增按钮：表单和表格之间左上角 -->
    <div style="margin-bottom: 10px; display: flex; justify-content: flex-start;">
      <el-button type="primary" @click="goToAddPage">新增</el-button>
    </div>
    <div class="table-container">
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        border
        :max-height="600"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="weaningDate" label="断奶日期" width="150" align="center">
          <template #default="scope">{{ formatDate(scope.row.weaningDate) }}</template>
        </el-table-column>
        <el-table-column prop="earTag" label="种母耳号" width="120" align="center">
          <template #default="scope">
            {{ formatEarTag(scope.row.earTag) }}
          </template>
        </el-table-column>
        <el-table-column prop="lactationDays" label="哺乳天数" width="100" align="center" />
        <el-table-column prop="breederWeight" label="种母重量(kg)" width="120" align="center" />
        <el-table-column prop="weaningLambCount" label="断奶只数" width="100" align="center" />
        <el-table-column prop="weaningTotalWeight" label="断奶总窝重(kg)" width="140" align="center" />
        <el-table-column prop="currentPen" label="当前栋舍" width="120" align="center">
          <template #default="scope">
            {{ formatBuilding(scope.row.currentPen) }}
          </template>
        </el-table-column>
        <el-table-column prop="currentStall" label="当前栏位" width="120" align="center">
          <template #default="scope">
            {{ formatPen(scope.row.currentStall) }}
          </template>
        </el-table-column>
        <el-table-column prop="transferInPen" label="转入栋舍" width="120" align="center">
          <template #default="scope">
            {{ formatBuilding(scope.row.transferInPen) }}
          </template>
        </el-table-column>
        <el-table-column prop="transferInStall" label="转入栏位" width="120" align="center">
          <template #default="scope">
            {{ formatPen(scope.row.transferInStall) }}
          </template>
        </el-table-column>
        <el-table-column prop="creator" label="创建人" width="100" align="center" />
        <el-table-column prop="responsiblePerson" label="负责人" width="100" align="center" />
        <el-table-column prop="createTime" label="创建时间" width="150" align="center">
          <template #default="scope">{{ formatDate(scope.row.createTime) }}</template>
        </el-table-column>
        <el-table-column prop="modifier" label="修改人" width="100" align="center" />
        <el-table-column prop="modifyTime" label="修改时间" width="150" align="center">
          <template #default="scope">{{ formatDate(scope.row.modifyTime) }}</template>
        </el-table-column>
        <el-table-column prop="approver" label="审核人" width="100" align="center" />
        <el-table-column prop="approvalTime" label="审核时间" width="150" align="center">
          <template #default="scope">{{ formatDate(scope.row.approvalTime) }}</template>
        </el-table-column>
        <el-table-column prop="documentNumber" label="单据号" width="120" align="center" />
        <el-table-column prop="weaningReason" label="断奶原因" width="120" align="center" />
        <el-table-column prop="status" label="状态" width="100" align="center" />
      </el-table>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getEweWeaningList } from '../../utils/EweWeaning'
import { useRouter } from 'vue-router'
import { serviceRead, Sheep_BreedingRead } from '../../utils/Interceptors'

const router = useRouter() // 修复：初始化 router 实例
const loading = ref(false)
const tableData = ref<any[]>([])
const responsiblePersonOptions = ref<Array<{label: string, value: string}>>([])
const earNumberMap = ref<Record<string, string>>({}) // 用于存储耳号ID到耳号名称的映射
const buildingMap = ref<Record<string, string>>({}) // 用于存储栋舍ID到名称的映射
const penMap = ref<Record<string, string>>({}) // 用于存储栏位ID到名称的映射

const searchForm = reactive({
  earTag: '',
  responsiblePerson: '',
  startDate: '',
  endDate: ''
})
const dateRange = ref<string[]>([])
const searchFormRef = ref()

// 获取耳号列表，用于将ID转换为显示名称
const fetchEarNumberList = async () => {
  try {
    const res = await Sheep_BreedingRead.get('/api/EliminationInfo/GetSheepFilesIdEarNumber')
    if (res.data && res.data.code === 200 && res.data.data) {
      // 构建耳号ID到名称的映射
      const map: Record<string, string> = {}
      res.data.data.forEach((item: any) => {
        if (item && item.Id && item.Name) {
          map[item.Id] = item.Name
        }
      })
      earNumberMap.value = map
      console.log('耳号映射表:', earNumberMap.value)
    }
  } catch (error) {
    console.error('获取耳号列表失败:', error)
  }
}

// 获取栋舍栏位列表
const fetchBuildingList = async () => {
  try {
    const res = await Sheep_BreedingRead.get('/api/Sheepfarm/SearchBuildingManagement', {
      params: { PageIndex: 1, PageSize: 100 }
    })
    if (res.data && res.data.code === 200 && res.data.PageData) {
      // 构建栏位ID到名称的映射
      const map: Record<string, string> = {}
      res.data.PageData.forEach((item: any) => {
        if (item && item.BuildingId && item.House_name) {
          map[item.BuildingId] = item.House_name
        }
      })
      buildingMap.value = map
      console.log('栏位映射表:', buildingMap.value)
    }
  } catch (error) {
    console.error('获取栏位列表失败:', error)
  }
}

// 获取栏号列表
const fetchPenList = async () => {
  try {
    const res = await Sheep_BreedingRead.get('/api/EliminationInfo/GetFieldManagementIdName')
    if (res.data && res.data.code === 200 && res.data.data) {
      // 构建栏号ID到名称的映射
      const map: Record<string, string> = {}
      res.data.data.forEach((item: any) => {
        if (item && item.Id && item.Name) {
          map[item.Id] = item.Name
        }
      })
      penMap.value = map
      console.log('栏号映射表:', penMap.value)
    }
  } catch (error) {
    console.error('获取栏号列表失败:', error)
  }
}

// 格式化种母耳号，将ID转换为名称
const formatEarTag = (earTagId: any) => {
  if (!earTagId) return '';
  
  // 处理可能是数字的情况
  const tagId = String(earTagId);
  
  // 检查映射表中是否有对应的名称
  if (earNumberMap.value && earNumberMap.value[tagId]) {
    return earNumberMap.value[tagId];
  }
  
  // 如果没有找到映射，返回原始ID
  return tagId;
}

// 格式化栋舍/栏位，将ID转换为名称
const formatBuilding = (buildingId: any) => {
  if (!buildingId) return '';
  
  // 处理可能是数字的情况
  const id = String(buildingId);
  
  // 检查映射表中是否有对应的名称
  if (buildingMap.value && buildingMap.value[id]) {
    return buildingMap.value[id];
  }
  
  // 如果没有找到映射，返回原始ID
  return id;
}

// 格式化栏号，将ID转换为名称
const formatPen = (penId: any) => {
  if (!penId) return '';
  
  // 处理可能是数字的情况
  const id = String(penId);
  
  // 检查映射表中是否有对应的名称
  if (penMap.value && penMap.value[id]) {
    return penMap.value[id];
  }
  
  // 如果没有找到映射，返回原始ID
  return id;
}

function formatDate(dateStr: string) {
  if (!dateStr) return ''
  const d = new Date(dateStr)
  if (isNaN(d.getTime())) return ''
  const y = d.getFullYear()
  const m = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  return `${y}-${m}-${day}`
}

function mapFields(list: any[]) {
  return list.map(item => ({
    id: item.Id,
    weaningDate: item.WeaningDate,
    earTag: item.EarTag,
    lactationDays: item.LactationDays,
    breederWeight: item.BreederWeight,
    weaningLambCount: item.WeaningLambCount,
    weaningTotalWeight: item.WeaningTotalWeight,
    currentPen: item.CurrentPen,
    currentStall: item.CurrentStall,
    transferInPen: item.TransferInPen,
    transferInStall: item.TransferInStall,
    creator: item.Creator,
    responsiblePerson: item.ResponsiblePerson,
    createTime: item.CreateTime,
    modifier: item.Modifier,
    modifyTime: item.ModifyTime,
    approver: item.Approver,
    approvalTime: item.ApprovalTime,
    documentNumber: item.DocumentNumber,
    weaningReason: item.WeaningReason,
    status: item.Status
  }))
}

function handleDateRangeChange(val: string[]) {
  if (val && val.length === 2) {
    searchForm.startDate = val[0]
    searchForm.endDate = val[1]
  } else {
    searchForm.startDate = ''
    searchForm.endDate = ''
  }
}

function handleSearch() {
  loading.value = true
  const params = {
    ...searchForm,
    startDate: dateRange.value[0] || undefined,
    endDate: dateRange.value[1] || undefined
  }
  
  // 确保所有映射表都已加载
  const loadAllMappings = async () => {
    const promises = []
    
    if (Object.keys(earNumberMap.value).length === 0) {
      promises.push(fetchEarNumberList())
    }
    
    if (Object.keys(buildingMap.value).length === 0) {
      promises.push(fetchBuildingList())
    }
    
    if (Object.keys(penMap.value).length === 0) {
      promises.push(fetchPenList())
    }
    
    if (promises.length > 0) {
      await Promise.all(promises)
    }
    
    getWeaningData(params)
  }
  
  loadAllMappings()
}

function getWeaningData(params: any) {
  getEweWeaningList(params)
    .then(res => {
      if (res.data && res.data.data) {
        tableData.value = mapFields(res.data.data)
      } else {
        tableData.value = []
      }
      loading.value = false
    }, () => {
      ElMessage.error('查询失败')
      loading.value = false
    })
}

function resetSearch() {
  Object.assign(searchForm, {
    earTag: '',
    responsiblePerson: '',
    startDate: '',
    endDate: ''
  })
  dateRange.value = []
  handleSearch()
}

// 跳转到新增页面
function goToAddPage() {
  router.push({ path: '/EweWeaningAdd' })
}

onMounted(async () => {
  // 获取用户列表
  try {
    const { data } = await serviceRead.get('/api/User/SraechUser', {
      params: { PageIndex: 1, PageSize: 100 }
    })
    if (data.code === 200 && Array.isArray(data.PageData)) {
      responsiblePersonOptions.value = data.PageData.map((user: any) => ({
        label: user.UserName,
        value: user.UserName
      }))
    } else {
      responsiblePersonOptions.value = []
    }
  } catch (e) {
    responsiblePersonOptions.value = []
    ElMessage.error('获取用户列表失败')
  }
  // 获取耳号列表
  fetchEarNumberList()
  // 获取栋舍栏位列表
  fetchBuildingList()
  // 获取栏号列表
  fetchPenList()
  handleSearch()
})
</script>

<style scoped>
.container {
  padding: 20px;
}
.search-container {
  margin-bottom: 20px;
}
.table-container {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
}
</style>
